import { Injectable } from '@angular/core';
import { BehaviorSubject ,  Observable } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';

@Injectable()
export class TableFlexService {

  private rows: HTMLElement[] = [];

  private flexSubject = new BehaviorSubject<Array<number| string>>(null);

  /** Get if rows is empty. */
  get empty(): boolean {
    return this.rows.filter((element: HTMLElement) =>
      element.localName === 'fui-table-row' && element.style.display !== 'none').length === 0;
  }

  constructor() {
    this.flexSubject.asObservable().pipe(
      distinctUntilChanged(),
    )
    .subscribe((flex) => {
      this.rows.forEach((row) => {
        this.setFlex(row, flex);
      });
    });
  }

  /** Register row element. */
  register(element: HTMLElement) {
    this.rows.push(element);
    const flex = this.flexSubject.getValue();
    this.setFlex(element, flex);
  }

  /** Unregister row element. */
  unregister(element: HTMLElement) {
    const idx = this.rows.indexOf(element);
    this.rows.splice(idx, 1);
  }

  /** Update flex values. */
  updateFlex(flex: (number | string)[]) {
    this.flexSubject.next(flex);
  }

  /** Set flex on a row element. */
  setFlex(row: HTMLElement, flex: Array<number| string>) {
    if (!Array.isArray(flex)) {
      return;
    }
    const childNodes: NodeList = row.childNodes;
    let count = 0;
    for (let i = 0; i < childNodes.length; i++) {
      const cell = childNodes[i] as HTMLElement;
      if (this.isTableCell(cell)) {
        this.setFlexCell(cell, flex, count ++);
      }
    }
  }

  private setFlexCell(cell: HTMLElement, flex: Array<number| string>, index: number) {
    let flexValue;
    try {
      flexValue = flex[index].toString();
    } catch (err) {
      flexValue = '0';
    }
    const [flexGrow, flexShrink = '0', flexBasis = '0%'] = flexValue.split(' ');
    const finalFlex = [flexGrow, flexShrink, flexBasis].join(' ');
    cell.style.flex = finalFlex;
    // 兼容IE10
    cell.style['msFlex'] = finalFlex;
  }

  private isTableCell(cell: HTMLElement) {
    if (cell.nodeType !== 1) {
      return false;
    }
    if (cell.classList.contains('fui-table-select-column')) {
      return false;
    }
    return true;
  }

}
